package cn.fun.spring4.chapter3.web;

import cn.fun.spring4.chapter3.domain.User;
import cn.fun.spring4.chapter3.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author zhangxf
 * @title LoginController
 * @date 2018/2/27
 * @description
 */
@Controller
@EnableTransactionManagement
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String login(){
        System.out.println("login......");
        return "login";
    }

    @RequestMapping("/loginCheck")
    public String loginCheck(LoginVO loginVO, HttpServletRequest request, HttpServletResponse response){
        System.out.println("checking...");
        boolean isValidUser = userService.hasMatchUser(loginVO.getUserName(), loginVO.getPassword());
        if (!isValidUser) {
            request.setAttribute("msg", "<font color='red'>登录失败</font>");
            return "login";
        } else {
            User user = userService.findUserByUserName(loginVO.getUserName());
            user.setLastIp(request.getLocalAddr());
            user.setLastVisit(new Date());
            userService.loginSuccess(user);
            request.getSession().setAttribute("user", user);
            return "main";
        }
    }
}
